<template>
  <div class="app-container">
    <el-tabs v-model="listQuery.status" type="card" style="margin-bottom:10px">
      <el-tab-pane v-for="item in type === 5 ? tab5 : tab6" :key="item.value" :label="item.label" :name="item.value+''">
      </el-tab-pane>
    </el-tabs>
    <div class="filter-container">
      <el-input v-model="listQuery.identifier" placeholder="订单编号" class="filter-item" />
      <el-input v-model="listQuery.originalIdentifier" placeholder="原始订单号" class="filter-item" />
      <el-input v-model="listQuery.gongyingName$lk" placeholder="供应商名称" v-if="userInfo.type === 1"
        class="filter-item" />
      <el-input v-model="listQuery.caigouName$lk" placeholder="采购商名称" v-if="userInfo.type === 2" class="filter-item" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter"
        >
        查询
      </el-button>
      <CreateOrderButton :type="type" :userInfo="userInfo" :orderStatusJson="orderStatusJson"
        :orderTypeJson="orderTypeJson" @handleCreate="handleCreate" style="margin-left:10px" />
      <el-button v-waves class="filter-item" type="primary" @click="$print($refs.print)"
        >
        打印列表数据
      </el-button>
    </div>
    <div style="margin-bottom:15px;color:#ff8704" v-if="createPsObject[type]">{{createPsObject[type]}}</div>
    <div style="position:relative">
      <div class="table" style="width: 100%;text-align:center;position: absolute;top:0;" ref="print">
        <h2 style="margin:10px;">{{type===5?'对账单':'结算单'}}</h2>
        <table style="width: 100%;text-align:center;border-collapse: collapse;word-break: break-all;" border="1"
          cellpadding="0" cellspacing="0">
          <tr>
            <th>序号</th>
            <th>订单编号</th>
            <th v-if="type===5">金额</th>
            <th v-if="userInfo.type === 1">供应商名称</th>
            <th v-else-if="userInfo.type === 2">采购商名称</th>
            <th>订单状态</th>
            <th>创建时间</th>
            <th>原始订单号</th>
            <th>交易明细</th>
            <th v-if="type===6">支付信息</th>
            <th v-if="type===6">支付备注</th>
          </tr>
          <tr v-for="(item, index) in list" :key="index">
            <td>{{index+1}}</td>
            <td>{{item.identifier}}</td>
            <td v-if="type===5">{{item.totalAmount}}</td>
            <td v-if="userInfo.type === 1">{{item.gongyingName}}</td>
            <td v-else-if="userInfo.type === 2">{{item.caigouName}}</td>
            <td>{{item.statusText}}</td>
            <td>{{item.createTime}}</td>
            <td>{{item.originalIdentifier}}</td>
            <td>{{item.detail}}</td>
            <td v-if="type===6">{{item.payTypeText}}<br />{{item.payNo}}</td>
            <td v-if="type===6">{{item.payRemark}}</td>
          </tr>
        </table>
      </div>
      <el-table v-loading="listLoading" :data="list" border fit highlight-current-row
        style="width: 100%;position: relative;">
        <el-table-column label="序号" type="index" align="center" width="60px" />
        <el-table-column label="订单编号" prop="identifier" align="center" />
        <el-table-column label="金额" prop="totalAmount" align="center" v-if="type===5" />
        <el-table-column label="供应商名称" prop="gongyingName" v-if="userInfo.type === 1" align="center" />
        <el-table-column label="采购商名称" prop="caigouName" v-else-if="userInfo.type === 2" align="center" />
        <el-table-column label="订单状态" prop="statusText" align="center" />
        <el-table-column label="创建时间" prop="createTime" align="center" width="160px" />
        <el-table-column label="原始订单号" prop="originalIdentifier" align="center" />
        <el-table-column label="交易明细" prop="detail" align="center" />
        <el-table-column label="支付信息" align="center" v-if="type===6">
          <template slot-scope="{row}">
            {{row.payTypeText}}<br />{{row.payNo}}
          </template>
        </el-table-column>
        <el-table-column label="支付备注" align="center" v-if="type===6">
          <template slot-scope="{row}">
            {{row.payRemark}}<br />
            <a class="no-print" download :href="row.payFile" v-if="row.payFile" style="color:#1890ff">下载附件</a>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220px"
          class="no-print">
          <template slot-scope="{row}">
            <ConfirmButton :row="row" :userInfo="userInfo" :orderStatusJson="orderStatusJson"
              :orderTypeJson="orderTypeJson" @handleConfirm="handleConfirm" />
            <CancelButton :row="row" :userInfo="userInfo" :orderStatusJson="orderStatusJson"
              :orderTypeJson="orderTypeJson" @handleCancel="handleCancel" />
            <el-button size="mini" @click="handleDetail(row)">详情</el-button>
            <SendButton :row="row" :userInfo="userInfo" :orderStatusJson="orderStatusJson"
              :orderTypeJson="orderTypeJson" @getList="getList" />
            <PayButton :row="row" :userInfo="userInfo" :orderStatusJson="orderStatusJson" :orderTypeJson="orderTypeJson"
              :driverList="driverList" @getList="getList" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

    <el-dialog title="确认订单" :visible.sync="dialogFormVisible" width="500px">
      <el-form :model="temp" ref="confirmForm" :rules="rules" label-position="right" label-width="100px"
        style="margin: 0 50px;">
        <el-form-item label="确认状态:">
          <el-radio-group v-model="temp.status">
            <el-radio :label="1">同意</el-radio>
            <el-radio :label="0">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="确认意见" prop="remark">
          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" />
        </el-form-item>
        <el-form-item label="确认凭证:">
          <Upload :default-image.sync="temp.image" :mode="6" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmOrder()">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="isCreateOrder?createTypeText:'订单详情'" :visible.sync="dialogDetailVisible" width="888px"
      v-if="orderDetail">
      <el-row :gutter="40">
        <el-col :span="8">订单编号：<span style="font-size:13px">{{orderDetail.identifier}}</span></el-col>
        <el-col :span="8">订单创建时间：{{orderDetail.createTime}}</el-col>
        <el-col :span="8">订单状态：{{orderDetail.statusText}}</el-col>
      </el-row>
      <el-row :gutter="40" v-if="type===5">
        <el-col :span="24">
          订单确认时间：{{orderDetail.handleTime}}
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="24">实付款（元）：{{orderDetail.totalAmount}}</el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="24">订单类型：{{orderDetail.typeText}}</el-col>
      </el-row>
      <el-row :gutter="40" v-if="orderDetail.payNo">
        <el-col :span="24">支付信息：{{orderDetail.payTypeText}}-{{orderDetail.payNo}}-{{orderDetail.payRemark}}</el-col>
      </el-row>
      <el-row :gutter="40" v-if="userInfo.type === 1 || userInfo.type === 2">
        <el-col :span="24" v-if="userInfo.type === 1">
          供应商名称：{{orderDetail.gongyingName}}<span style="margin-left:10px"></span>{{orderDetail.gongyingMobile}}
        </el-col>
        <el-col :span="24" v-else-if="userInfo.type === 2">
          采购商名称：{{orderDetail.caigouName}}<span style="margin-left:10px"></span>{{orderDetail.caigouMobile}}
        </el-col>
      </el-row>
      <el-row :gutter="40" v-if="orderDetail.originalIdentifier">
        <el-col :span="24">
          原始单据号：{{orderDetail.originalIdentifier}}
        </el-col>
      </el-row>
      <!-- <el-row :gutter="40">
        <el-col :span="24">备注：{{orderDetail.remark}}</el-col>
      </el-row> -->

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogDetailVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="isCreateOrder ? createOrder():dialogDetailVisible = false">
          确定
        </el-button>
      </div>
    </el-dialog>
    <!-- <iframe :id="'print-iframe'+type" style="width: 0px; height: 0px" frameborder="0"></iframe> -->
    <!-- <el-table :id="'print-content'+type" :data="list" border
      style="width: 100%;text-align:center;border-collapse: collapse;word-break: break-all;">
      <el-table-column label="序号" type="index" align="center" width="60px" />
      <el-table-column label="订单编号" prop="identifier" align="center" />
      <el-table-column label="金额" prop="totalAmount" align="center" v-if="type===5" />
      <el-table-column label="供应商名称" prop="gongyingName" v-if="userInfo.type === 1" align="center" />
      <el-table-column label="采购商名称" prop="caigouName" v-else-if="userInfo.type === 2" align="center" />
      <el-table-column label="订单状态" prop="statusText" align="center" />
      <el-table-column label="创建时间" prop="createTime" align="center" width="160px" />
      <el-table-column label="原始订单号" prop="originalIdentifier" align="center" />
      <el-table-column label="交易明细" prop="detail" align="center" />
      <el-table-column label="支付信息" align="center" v-if="type===6">
        <template slot-scope="{row}">
          {{row.payTypeText}}<br />{{row.payNo}}
        </template>
      </el-table-column>
      <el-table-column label="支付备注" align="center" v-if="type===6">
        <template slot-scope="{row}">
          {{row.payRemark}}
        </template>
      </el-table-column>
    </el-table> -->
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { orderPageByQo, orderCancel, orderHandle, orderStatusJson, orderTypeJson, orderGetById, orderCreate } from '@/api/mall'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
import CreateOrderButton from './CreateOrderButton'
import ConfirmButton from './ConfirmButton'
import CancelButton from './CancelButton'
import SendButton from './SendButton'
import PayButton from './PayButton'
import Upload from '@/components/Upload'
import NumInput from '@/components/NumInput'
import DatePicker from '@/components/DatePicker'
import qs from 'qs'
import { createPsObject, tab5, tab6 } from '../constant'


export default {
  name: "Order",
  directives: { waves },
  components: { Pagination, CreateOrderButton, ConfirmButton, CancelButton, SendButton, PayButton, Upload, NumInput, DatePicker },
  props: {
    type: {
      default: 5,
      type: Number,
    },
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        type: '',
        status: '1',
        identifier: '',
        originalIdentifier: '',
        gongyingName$lk: '',
        caigouName$lk: '',
        createTime$gte: '',
        createTime$lte: '',
      },
      temp: {
        id: 0,
        remark: "",
        image: "",
        status: 1
      },
      dialogFormVisible: false,
      dialogDetailVisible: false,
      rules: {
        remark: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      driverList: [],
      orderTypeJson: orderTypeJson(),
      orderStatusJson: orderStatusJson(),
      tab5,
      tab6,
      orderDetail: '',
      //创建XX单，公用详情弹窗，isCreateOrder时为创建
      isCreateOrder: false,
      createId: '',
      createType: '',
      createTypeText: '',
      createUpTypeText: '',
      createPsObject
    }
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  watch: {
    'listQuery.status': function () {
      this.handleFilter()
    },
    'temp.status': function (val) {
      this.temp.remark = val ? '同意' : '驳回';
    }
  },
  created() {
    this.listQuery.type = this.type
    if (this.$route.query.status && this.listQuery.status !== this.$route.query.status.toString()) {
      this.listQuery.status = this.$route.query.status.toString()
    } else {
      if (this.type === 6) {
        this.listQuery.status = '2'
      } else {
        this.getList()
      }
    }
  },
  methods: {
    getList() {
      this.listLoading = true;
      orderPageByQo(this.listQuery).then((response) => {
        this.list = response.list || [];
        this.total = response.totalCount;
        this.listLoading = false;
      });
    },
    handleFilter() {
      this.listQuery.pageNo = 1;
      this.getList();
    },
    handleConfirm(row) {
      this.temp.id = row.id;
      this.temp.status = 1;
      this.temp.remark = "同意";
      this.temp.image = "";
      this.dialogFormVisible = true;
    },
    confirmOrder() {
      this.$refs["confirmForm"].validate((valid) => {
        if (valid) {
          orderHandle(this.temp).then(() => {
            this.getList();
            this.dialogFormVisible = false;
            // this.$notify({
            //   title: "成功",
            //   message: "操作成功",
            //   type: "success",
            //   duration: 2000,
            // });

            this.$message({
              message: '操作成功',
              type: 'success'
            });
          });
        }
      });
    },
    handleCancel(row) {
      this.$confirm("是否确认取消订单？").then(() => {
        orderCancel({ id: row.id }).then(() => {
          this.getList();
          // this.$notify({
          //   title: "成功",
          //   message: "操作成功",
          //   type: "success",
          //   duration: 2000,
          // });

          this.$message({
            message: '操作成功',
            type: 'success'
          });
      });
      });
    },
    handleDetail(row) {
      this.isCreateOrder = false
      this.getDetail(row.id).then(res => {
        this.orderDetail = Object.assign({}, res)
        this.dialogDetailVisible = true;
      })
    },
    handleCreate(id, createType, createTypeText, createUpTypeText) {
      this.isCreateOrder = true
      this.createType = createType
      this.createId = id
      this.createTypeText = '创建' + createTypeText
      //选择的上级订单
      this.createUpTypeText = '选择' + createUpTypeText
      this.orderUpListSelect = {}
      // this.getDetail(id).then(res => {
      //   this.orderDetail = Object.assign({}, res)
      //   this.dialogDetailVisible = true;
      // })
      this.createOrder()
    },
    createOrder() {
      const params = {
        originalId: this.createId,
        type: this.createType,
      }
      orderCreate(qs.stringify(params)).then(() => {
        this.dialogDetailVisible = false;
        this.getList()
        // this.$notify({
        //   title: '成功',
        //   message: '操作成功',
        //   type: 'success',
        //   duration: 2000
        // })

        this.$message({
          message: '操作成功',
          type: 'success'
        });
      }).catch(() => {
        this.dialogDetailVisible = false;
      })
    },
    getDetail(id) {
      return new Promise((resolve, reject) => {
        orderGetById({ id: id })
          .then(res => {
            resolve(res);
          })
          .catch(err => {
            reject(err);
          });
      });
    },
  }
}
</script>
<style lang="scss" scoped>
.el-row {
  line-height: 2;
  font-size: 15px;
}
.searchItem {
  display: flex;
  align-items: center;
  .searchLabel {
    color: #666;
  }
}
.box-card {
  margin: 20px 0;
  .flexItem {
    display: flex;
    align-items: center;
    .fuhao {
      margin-right: 3px;
      font-size: 16px;
      color: red;
    }
    .el-input {
      width: auto;
      flex: 1;
    }
  }
}
</style>
